<?php


namespace app\controller\api;


use app\BaseController;
use app\models\coupon\CouponModel;
use app\models\coupon\UserCouponModel;
use app\services\order\CouponService;
use app\services\user\UserCouponService;

class CouponController extends BaseController
{

    public function checkCoupon(){
        try {
            $goods_id = $this->request->param('goods_id');
            if(is_array($goods_id)){
                return $this->success();
            }
            $ids = self::getCanUsedCouponIdArr($this->request->userId,$goods_id,0);
            $list = UserCouponModel::where('id','in',$ids)
                ->field('id,coupon_id,is_used,status,coupon_name,coupon_type,amount,use_start_time,use_end_time,use_type,type_id')
                ->select()
                ->each(function($item){
                    $item['use_start_time'] = date('Y-m-d H:i:s',$item['use_start_time']);
                    $item['use_end_time'] = date('Y-m-d H:i:s',$item['use_end_time']);
                    return $item;
                });
            return $this->success($list);
        }catch (\Exception $exception){
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 获取优惠券列表
     * @return array|\think\response\Json
     */
    public function getUserCouponList()
    {
        try {
            $userId = $this->request->userId;
            $where = [];
            $where[] = ['user_id', '=', $userId];
            $where[] = ['is_used', '=', 0];
            $where[] = ['status', '=', 0];
            $type = $this->request->param('type', 0, 'int');
            // 可用列表
            if ($type == 1) {
//                $where = ['use_start_time','<=',time()];
                $where[] = ['use_end_time','>',time()];
            }
            // 已过期
            if ($type == 2) {
                $where[] = ['use_end_time','<',time()];
            }
            $list['data'] = UserCouponModel::where($where)
                ->order('amount', 'desc')
                ->field('id,coupon_id,is_used,status,coupon_name,coupon_type,amount,use_start_time,use_end_time,use_type,type_id')
                ->select()
                ->toArray();
            foreach ($list['data'] as &$v) {
//                $v['can_use'] = $v['reason'] == '' ? 1 : 0;
                $v['use_end_time'] = date('Y-m-d', $v['use_end_time']);
                $v['use_start_time'] = date('Y-m-d', $v['use_start_time']);
            }
            if ($type == 0 && $list['total'] > 0) {
                $arr = arraySequence($list['data'], 'can_use', 'SORT_DESC');
                $list['data'] = $arr;
            }
            return $this->success($list['data']);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 用户所有优惠券
     * @param $userId
     * @return array
     */
    private function getUserCouponIdArr($userId)
    {
        $arr = UserCouponModel::where('user_id', $userId)
            ->where('is_used', 0)
            ->where('status', 0)
            ->column('id');
        return $arr;
    }

    /**
     * 优惠券可用列表
     * @param $userId
     * @param $goodsId
     * @param $amount
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    private function getCanUsedCouponIdArr($userId, $goodsId, $amount)
    {
//        if (!$goodsId || !$amount) {
//            $arr = UserCouponModel::where('user_id', $userId)
//                ->where('is_used', 0)
//                ->where('status', 0)
//                ->where('use_start_time', '<=', time())
//                ->where('use_end_time', '>=', time())
//                ->column('id');
//            return $arr;
//        }
        $list = UserCouponModel::where('user_id', $userId)
            ->where('is_used', 0)
            ->where('status', 0)
//            ->where('less_amount', '<=', $amount)
            ->where('use_start_time', '<=', time())
            ->where('use_end_time', '>=', time())
            ->select()
            ->toArray();
        if (!$list) {
            return [];
        }
        $arr = [];
        foreach ($list as $value) {
            // 使用商品 0全部可用 1指定商品可用 2指定商品不可用
            $type = $value['use_type'];
            $typeIdArr = json_decode($value['type_id'],true);
            if ($type == 0 || ($type == 1 && in_array($goodsId, $typeIdArr)) || ($type == 2 && !in_array($goodsId, $typeIdArr))) {
                array_push($arr, $value['id']);
            }
        }
        return $arr;
    }

    /**
     * 检测是否有可领的优惠券
     * @return \think\response\Json
     */
    public function getCoupon()
    {
        try {
            $userId = $this->request->userId;
            $couponList = CouponModel::where('start_time', '<=', time())
                ->where('end_time', '>=', time())
                ->where('type', 0)
                ->order('id', 'desc')
                ->select();
            $amount = 0;
            foreach ($couponList as $v) {
                $getAmount = UserCouponService::checkCouponCanGet($userId, $v);
                if ($getAmount) {
                    $amount += $getAmount;
                    UserCouponService::sendCoupon([$userId], $v['id']);
                }
            }
            return $this->success($amount);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }
}